package com.ff.neuropp.service;

import com.ff.neuropp.Dto.ClassMate;
import com.ff.neuropp.domain.Course;
import com.ff.neuropp.domain.CourseCategory;
import com.ff.neuropp.domain.IosUser;
import com.ff.neuropp.domain.Order;
import com.ff.neuropp.repository.CourseCategoryRepository;
import com.ff.neuropp.repository.CourseRepository;
import com.ff.neuropp.repository.IosUserRepository;
import com.ff.neuropp.repository.OrderRepository;
import com.ff.neuropp.response.CourseDetailinfo;
import com.ff.neuropp.response.CourseResponse;
import com.ff.neuropp.util.ResultTool;
import com.ff.neuropp.util.SpecificationUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程信息服务
 */
@Service
public class AppCourseService {

	@Resource
	private CourseRepository courseDao;

	@Resource
	private CourseCategoryRepository categoryDao;
	
	@Resource
	private OrderRepository orderRepository;
	@Resource
	private IosUserRepository iosUserRepository;
	

	interface STATUS{
		//上线
		Integer ON = 1;
		//下线
		Integer OFF = 0;
	}

	
    /**
    * 课程列表查询
     * @return
     */
    public Map<String,Object> courseList(String param){
        Map<String,Object> result = new HashMap<>();
        List<CourseResponse> courseList = new ArrayList<>();
        //查询非下线的课程分类
		if(StringUtils.isNotEmpty(param)){
			//搜索匹配课程
			List<CourseCategory>  list = categoryDao.findAllByStatusAndNameLike(STATUS.ON,"%"+param+"%");
			//模糊匹配课程分类
			if(!list.isEmpty()){
				list.forEach(type->{
					List<Course> courses = courseDao.findAllByCategory_idAndStatus(type.getId(),STATUS.ON);
					CourseResponse out = new CourseResponse(type.getName(),courses);
					courseList.add(out);
				});
			}else{
				//模糊匹配课程
				List<Course> arr = courseDao.findAllByStatusAndCourseNameLike(STATUS.ON,"%"+param+"%");
				Map<Integer,Object> hash = new HashMap<>();
				if(!arr.isEmpty()){
					arr.forEach(o->{
						CourseCategory type = categoryDao.findByIdAndStatus(o.getCategory().getId(),STATUS.ON);
						hash.put(type.getId(),type.getName());
					});
					//数据组装
					hash.forEach((k,v)->{
						List<Course> temp = arr.stream().filter(s-> k.equals(s.getCategory().getId())).collect(Collectors.toList());
						CourseResponse out = new CourseResponse(String.valueOf(v),temp);
						courseList.add(out);
					});
				}
			}
		}else{
			//全部课程
			List<CourseCategory> typeList= categoryDao.findAllByStatus(STATUS.ON);
			if (typeList!=null && typeList.size()>0){
				typeList.forEach(type->{
					List<Course> courses = courseDao.findAllByCategory_idAndStatus(type.getId(),STATUS.ON);
					CourseResponse out = new CourseResponse(type.getName(),courses);
					courseList.add(out);
				});
			}
		}
        return ResultTool.genSuccessResult(courseList);
    }
	
	
	

	/**
	 * 课程详情查询
	 * 
	 * @param id
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public Map<String, Object> courseDetail(Integer id)  {
		Optional<Course> info = courseDao.findById(id);
		if (info.isPresent()) {
			Course course=info.get();
			List<ClassMate>  list=new ArrayList<>();
			CourseDetailinfo courseDetailinfo=new CourseDetailinfo();
			courseDetailinfo.setId(course.getId());
			courseDetailinfo.setCategory(course.getCategory());
			courseDetailinfo.setCategoryName(course.getCategoryName());
			courseDetailinfo.setCourseName(course.getCourseName());
			courseDetailinfo.setCourseImage(course.getCourseImage());
			courseDetailinfo.setIntro(course.getIntro());
			courseDetailinfo.setSeatTotal(course.getSeatTotal());
			courseDetailinfo.setSeatingCount(course.getSeatingCount());
			courseDetailinfo.setCourseDesc(course.getCourseDesc());
			courseDetailinfo.setMentor(course.getMentor());
			courseDetailinfo.setCourseLocation(course.getCourseLocation());
			courseDetailinfo.setCoursePrice(course.getCoursePrice());
			courseDetailinfo.setIsCanCoupon(course.getIsCanCoupon());
			courseDetailinfo.setCouponList(course.getCouponList());
			courseDetailinfo.setWorkList(course.getWorkList());
			courseDetailinfo.setCourseWareList(course.getCourseWareList());
			courseDetailinfo.setCourseDateList(course.getCourseDateList());
			courseDetailinfo.setServeFee(course.getServeFee());
			courseDetailinfo.setCourseLevel(course.getCourseLevel());
			courseDetailinfo.setCareerId(course.getCareerId());
			courseDetailinfo.setCareerPoint(course.getCareerPoint());
			courseDetailinfo.setStatus(course.getStatus());
			courseDetailinfo.setCreateDate(course.getCreateDate());
			courseDetailinfo.setUpdateTime(course.getUpdateTime());
			//查询每个课程的同班同学
			List<Order> orderList = orderRepository.findAllByCourse_idAndOrderStatus(course.getId(),1);
			orderList.forEach(order->{
				ClassMate cm=new ClassMate();
				//IosUser iosUser=order.getIosUser();
				IosUser iosUser=iosUserRepository.findByUserId(order.getUserId());
				cm.setClassMateId(order.getUserId());
				cm.setClassMateName(iosUser.getUserName());
				cm.setClassMateHeadUrl(iosUser.getHeadUrl());
				list.add(cm);
			});
			//BeanUtils.copyProperties(course, courseDetailinfo);
			courseDetailinfo.setClassMateList(list);
			List<com.ff.neuropp.domain.Work> works=course.getWorkList();
			List<com.ff.neuropp.domain.Work>  effectWorkList=new ArrayList<>();
			works.forEach(work->{
				Date now=new Date();
				int compareTo = work.getWorkEndTime().compareTo(now);
				//作业结束时间小于当前时间返回-1，作业结束时间大于当前时间返回1，相等返回0
				if(compareTo>0) {
					effectWorkList.add(work);
				}
			});
			courseDetailinfo.setEffectWorkList(effectWorkList);
			return ResultTool.genSuccessResult(courseDetailinfo);
			
		}
		return ResultTool.genSuccessResult("未查询到课程详情");
	}

	/**
	 * 
	 * pc 课程查询列表
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param param
	 * @return
	 */
	public Page<Course> findPage(Integer pageNo, Integer pageSize, Map<String, Object> param) {
		Sort.Direction direction = Sort.Direction.DESC;
		String sort = "id";
		Pageable pageable = new PageRequest(pageNo - 1, pageSize, direction, sort);
		return courseDao.findAll(SpecificationUtil.buildSpecification(param, Course.class), pageable);
	}

	/**
	 * 添加课程
	 * 
	 * @param course
	 * @return
	 */
	public Course saveCourse(@Valid Course course) {
		return courseDao.save(course);
	}

	/**
	 * 根据id 删除实体
	 * @param id
	 */
	public void deleteById(Integer id) {
		courseDao.deleteById(id);
	}

	/**
	 * 查询课程详情
	 * 
	 * @param id
	 * @return
	 */
	public Course findById(Integer id) {
		Optional<Course> optional = courseDao.findById(id);
		if (optional.isPresent()) {
			return optional.get();
		} else {
			return null;
		}
	}

}
